package com.idbk.chargestation.adapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.pile.ActivityPointDetail;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.app.MyVersion;
import com.idbk.chargestation.bean.JsonPointsOverview;
import com.idbk.chargestation.bll.pile.PileVendors;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.MapUtil;

import java.util.List;
import java.util.Locale;

/**
 * 充电点列表 适配器（充电点列表，我的收藏）
 *
 * @author lupc
 */
public class PointListAdapter extends BaseAdapter {

    private Context mContext;
    private List<JsonPointsOverview> mList;
    private LayoutInflater mInflater;

    private boolean mIsLongClickCancelCollection = false;

    public PointListAdapter(Context context, List<JsonPointsOverview> list) {
        mList = list;
        mInflater = LayoutInflater.from(context);
        mContext = context;
    }

    /*
     * 设置长按 取消收藏
     */
    public void setLongClickCancelCollection(boolean r) {
        mIsLongClickCancelCollection = r;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v;
        PointInfoHold hold;
        if (convertView == null) {
            v = mInflater.inflate(R.layout.layout_point_info_2, parent, false);
            hold = new PointInfoHold();
            hold.initView(v);
            v.setTag(hold);
        } else {
            v = convertView;
            hold = (PointInfoHold) v.getTag();
        }

        bindView(position, v, hold);

        return v;
    }

    private void bindView(final int position, View convertView, PointInfoHold hold) {
        final JsonPointsOverview item = mList.get(position);

        hold.fillData(mContext, item, position);

        //导航
        convertView.findViewById(R.id.layout_navi).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MapUtil.startNavi(mContext, item.lat, item.lng);
            }
        });
        //详情
        convertView.findViewById(R.id.layout_detail).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ActivityPointDetail.class);
                intent.putExtra(Const.KEY_ID, item.id);
                ((Activity) mContext).startActivityForResult(intent, Const.CODE_REQUEST_POINT);
            }
        });
        //长按时候是否取消收藏
        if (mIsLongClickCancelCollection) {
            convertView.setOnLongClickListener(new View.OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    new AlertDialog.Builder(mContext)
                            .setMessage("你确实要取消这条收藏吗？")
                            .setNegativeButton(R.string.common_cancel, null)
                            .setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    final ProgressDialog pDialog = ProgressDialog.show(
                                            mContext, null, "提交中...", true, false);
                                    ChargeStationAPI.cancelCollectPoint(item.id, new EHttpResponse() {

                                        @Override
                                        public void onEResponse(String response) {
                                            mList.remove(position);
                                            notifyDataSetChanged();
                                        }

                                        @Override
                                        public void onEErrorResponse(VolleyError error) {
                                            Toast.makeText(mContext, "取消收藏失败！", Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onEFinish() {
                                            super.onEFinish();
                                            pDialog.dismiss();
                                        }

                                    });
                                }
                            })
                            .create()
                            .show();
                    return true;
                }
            });
        }
    }

    public static class PointInfoHold {
        private TextView mTextTitle, mTextAddress, mTextPileCount, mTextDistance, mTextPointTag;
        private RatingBar mRatingPoint;
        private ImageView mImageAuthority;

        public void initView(View parent) {
            mTextTitle = (TextView) parent.findViewById(R.id.textview_title);
            mTextAddress = (TextView) parent.findViewById(R.id.textview_address);

            mTextPointTag = (TextView) parent.findViewById(R.id.textview_point_tag);
            mTextDistance = (TextView) parent.findViewById(R.id.textview_distance);
            mTextPileCount = (TextView) parent.findViewById(R.id.textview_pile_count);

            mImageAuthority = (ImageView) parent.findViewById(R.id.imageview_authority);

            mRatingPoint = (RatingBar) parent.findViewById(R.id.ratingbar_point);
        }

        public void fillData(Context context, JsonPointsOverview data) {
            fillData(context, data, -1);
        }

        private void fillData(Context context, JsonPointsOverview data, int position) {
            //充电点名称
            if (position == -1) {
                mTextTitle.setText(data.name);
            } else {
                mTextTitle.setText((position + 1) + "." + data.name);
            }

            if (MyVersion.getVersion(context).equals(MyVersion.VERSION_ZNYD)) {
                if (data.operatorId == PileVendors.OFFICAL || data.operatorId == PileVendors.YI_DIAN_ZHUANG) {
                    mImageAuthority.setVisibility(View.VISIBLE);
                } else {
                    mImageAuthority.setVisibility(View.INVISIBLE);
                }
            } else {
                mImageAuthority.setVisibility(View.INVISIBLE);
            }
            mTextAddress.setText(data.address);//充电点地址
            //计算距离
            String distance = MapUtil.calculateDistance(data.lat, data.lng);
            mTextDistance.setText(distance);

            //评分
            float mark = 4.5f;
            if (data.mark != null) {
                try {
                    mark = Float.parseFloat(data.mark);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mRatingPoint.setRating(mark);

            //
            StringBuilder sb = new StringBuilder();
            //是否免费
            if (data.isFree) {
                sb.append("免费充电");
            } else {
                sb.append("收费充电");
            }
            //是否对外开放
            sb.append(" | ");
            if (data.isOpening) {
                sb.append("对外开放");
            } else {
                sb.append("对内开放");
            }
            //是否支持预约
            sb.append(" | ");
            if (data.bookSupport) {
                sb.append("支持预约");
            } else {
                sb.append("不可预约");
            }
            mTextPointTag.setText(sb.toString());

            //
            String s = String.format(
                    Locale.CHINA,
                    "空闲电桩/总电桩：<font color='#5dd139'>%s/%s</font>",
                    data.idleNum,
                    data.count4Pile);
            mTextPileCount.setText(Html.fromHtml(s));
        }
    }

}

